package com.macaline.framemarker.dataBase.mysql.session;


import com.macaline.framemarker.dataBase.framework.bean.Table;
import com.macaline.framemarker.dataBase.framework.session.AbstractDataBaseSession;
import com.macaline.framemarker.dataBase.mysql.util.SqlUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MySQL数据库操作session
 */
public class MySQLSession extends AbstractDataBaseSession {


    @Override
    public void selTableList(Table table) throws SQLException {

    }

    @Override
    public void createTable(Table table) throws Exception {
        String insertSql = SqlUtil.getInsertSql(table);
        Boolean execute = execute(insertSql);
    }

    @Override
    public void dropTable(Table table) throws SQLException {
        execute(SqlUtil.getDropTable(table.getName()));
    }

    /**
     * 删除表
     * @param tableName 表名称
     * @throws SQLException
     */
    public void dropTable(String tableName) throws SQLException {
        execute(SqlUtil.getDropTable(tableName));
    }

    @Override
    public void delColumn(Table table) {

    }

    @Override
    public void addColumn(Table table) {

    }

    /**
     * 执行sql语句
     * @param sql sql语句
     * @return
     * @throws SQLException
     */
    public List<Map> executeQuery(String sql) throws SQLException {
        Connection connection = getConnection();
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        List<Map> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取列的数量
        while (rs.next()) {
            Map<String, Object> rowData = new HashMap<>();//声明Map
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
            }
            list.add(rowData);
        }
        close(connection);
        return list;
    }

    /**
     * 查看表是否存在
     * @param table 表信息
     * @return
     * @throws SQLException
     */
    public Boolean isExistsTab(Table table) throws SQLException {
        return isExistsTab(table.getName());
    }
    /**
     * 查看表是否存在
     * @param tableName 表名
     * @return
     * @throws SQLException
     */
    public Boolean isExistsTab(String tableName) throws SQLException {
        String sql = "select * from information_schema.TABLES where TABLE_NAME = '" + tableName + "'";
        List<Map> list = executeQuery(sql);
        if(list.isEmpty()){
            return false;
        }
        return true;
    }
}
